package com.berchen.ReadWriteLock读写锁;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁：什么情况下用读写锁?
 *
 * 写写、读写 互斥（同一时刻只有一个线程访问共享资源。）
 * 读读：不需要互斥。
 */
public class TestReadWriteLock {
    public static void main(String[] args){

        ReadWriteLockDemo ld=new ReadWriteLockDemo();

        new Thread(new Runnable() {
            @Override
            public void run() {
                ld.write((int) (Math.random()*100));

            }
        },"write").start();

        for(int i=0;i<10;i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    ld.read();
                }
            }, "read").start();
        }
    }
}
class ReadWriteLockDemo{

    private int num=0;

    private ReadWriteLock lock=new ReentrantReadWriteLock();    // 读写锁
    // 读,可以多个线程同时进行读
    public void read(){

        lock.readLock().lock(); // 上读的锁
        try{
            System.out.println(Thread.currentThread().getName()+" : "+num);
        }
        finally {
            lock.readLock().unlock();   // 释放读的锁
        }
    }
    // 写
    public void write(int num){

        lock.writeLock().lock();    // 添加写的锁
        try{

            this.num=num;
            System.out.println(Thread.currentThread().getName()+" : 写");
        }
        finally {

            lock.writeLock().unlock();  // 释放写的锁
        }
    }
}
